<template>
  <div class="all">
    <template>
      <!--  用户编辑对话框  -->
        <el-form :model="userForm" ref="userFormRef" :rules="rules" :disabled="!editMyinfo">
          <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
            <el-input v-model="userForm.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="登录密码" prop="password" :label-width="formLabelWidth">
            <el-input type="password" placeholder="修改密码" v-model="userForm.password" autocomplete="off"></el-input>
          </el-form-item>
<!--          <el-form-item label="确认密码" prop="password" :label-width="formLabelWidth">-->
<!--            <el-input type="password" v-model="userForm.password" autocomplete="off"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="电子邮件" prop="email" :label-width="formLabelWidth">
            <el-input v-model="userForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone" :label-width="formLabelWidth">
            <el-input v-model="userForm.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="注册时间" :label-width="formLabelWidth">
            <el-input v-model="userForm.registerTime" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="上次登录时间" :label-width="formLabelWidth">
            <el-input v-model="userForm.lastLogin" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户状态" :label-width="formLabelWidth">
            <el-switch
              v-model="userForm.status"
              :active-value="0"
              active-text="正常"
              :inactive-value="1"
              inactive-text="封禁"
              disabled
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="用户角色" :label-width="formLabelWidth">
            <template>
              <el-checkbox-group
                v-model="userForm.roleIdList"
                style="width: 55%"
                :max="3"
              >
                <el-checkbox v-for="role in roleList" :label="role.id" :key="role.id" disabled>{{role.name}}</el-checkbox>
              </el-checkbox-group>
            </template>

          </el-form-item>



        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="openEdit">{{editBtn}}</el-button>
          <el-button type="primary" @click="saveUser" v-if="editMyinfo">确 定</el-button>
        </div>
    </template>

  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
// 例如：import  《组件名称》  from '《组件路径》 ';
import userApi from '@/api/userManage'
import roleApi from '@/api/roleManage'
import infoApi from '@/api/personal'
import { getToken } from '@/utils/auth'

export default {
  // import 引入的组件需要注入到对象中才能使用
  data () {
    var checkEmail = (rule, value, callback) => {
      var reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
      if (!reg.test(value)) {
        return callback(new Error('邮箱格式错误'));
      }
      callback();
    };
    var checkPhone = (rule, value, callback) => {
      var reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
      if (!reg.test(value)) {
        return callback(new Error('电话号码格式错误'));
      }
      callback();
    };
    // 这里存放数据
    return {
      user: {
        name: '',
        pwd: '',
        em: '',
        ph: '',
        id: 0,
      },
      roleList: [

      ],
      editMyinfo: false,
      editBtn: '编辑',
      editBtnType: 'succcess',
      title: '我的信息',
      dialogFormVisible: true,
      formLabelWidth: '130px',
      userList: [],
      userForm: {
        roleIdList: [],
        id: 0
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: false, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入电子邮件', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur'}
        ],
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur'}
        ],
      },

    }
  },
  // 计算属性 类似于 data 概念
  computed: {},
  // 监控 data 中的数据变化
  watch: {},
  // 方法集合
  methods: {
    openEdit() {
      if (this.editMyinfo) {
        this.userForm.username = this.user.username;
        this.userForm.email = this.user.em;
        this.userForm.phone = this.user.ph;
        this.userForm.password = this.user.pwd;
        this.editMyinfo = false;
        this.editBtn = '编辑';
        this.editBtnType = 'succcess';
        // 清空表单校验状态
        this.$refs.userFormRef.clearValidate();
      } else {
        console.log(this.user)
        this.editMyinfo = true;
        this.editBtn = '取消';
        this.editBtnType = 'info';
      }
    },
    getAllRoleList() {
      roleApi.getAllRoleList().then( response => {
        this.roleList = response.data;
      });
    },
    getUserInfo() {
      infoApi.getCurUser(getToken()).then( response => {
        console.log('getCurUser')
        this.user.id = response.data.id;
        console.log(this.user.id)

        userApi.getUserById(this.user.id).then( response => {
          console.log(response.data)
          this.userForm = response.data;
          this.userForm.password = '';
          this.user.username = response.data.username;
          this.user.em = response.data.email;
          this.user.ph = response.data.phone;
          console.log(this.user.name)
          console.log('getUserById')
          console.log(this.userForm)
        });
      });
    },
    saveUser() {
      this.$refs.userFormRef.validate((valid) => {
        if (valid) {
          // 提交后端
          userApi.saveMyInfo(this.userForm).then( response => {
            // 成功提示
            this.$message({
              message: response.message,
              type: 'success'
            });
            // 切换为不可输入
            this.editMyinfo = false;
            // 刷新表格
            this.getUserInfo();
          });
        } else {
          return false;
        }
      });
    },
  },
  // 生命周期 - 创建完成（可以访问当前this 实例）
  created () {
    this.getUserInfo();
    this.getAllRoleList();
  },
  // 生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted () {
  },
  beforeCreate (){
  },
  beforeMount () {
  }, // 生命周期 - 挂载之前
  beforeUpdate () {
  }, // 生命周期 - 更新之前
  updated () {
  }, // 生命周期 - 更新之后
  beforeDestroy () {
  }, // 生命周期 - 销毁之前
  destroyed () {
  }, // 生命周期 - 销毁完成
  activated () {
  } // 如果页面有 keep-alive 缓存功能,这个函数会触发
}
</script>

<style scoped>
.all{
  align-items: center;
}
</style>
